import type { GreasyForkElements } from '../../../../../../../../types/constants/personalization/greasy_fork'
import { ThemeVarService } from '../../../../../../../../lib/abstract/style/theme_var/service'
import { ICON_IDS } from '../../../../../../../../lib/icons/types/constants'
import { PageHandler } from '../../../../../../../../lib/page_handler'
import {
  getGreasyForkPageCategory,
  GreasyForkPageCategory,
  GreasyForkPageType,
} from '../../../../../../../../lib/page_handler/platform/greasyfork/types'
import { ToolKit } from '../../../../../../../../lib/utils/toolkit'
import {
  FeedbackDataMarkerType,
  generateScriptTagStyles,
  ScriptDataMarkerType,
} from '../../../../../../../../module/page_enhancer/data_presentation/platform/greasy_fork/script_valuation/types'
import {
  BodyClasses,
  BUTTON_STYLES,
  getAllAlertSelector,
  logger,
  PAGE_ELEMENTS,
  PROJECT_PREFIX,
  SUPPORTED_PLATFORMS,
  themeClassPrefix,
  TITLE_STYLES,
} from '../../../../../../../../types/constants'
import { getElementSelector } from '../../../../../../../../types/constants/personalization/common'
import { StylesService } from '../../../../../../../../types/constants/styles'
import {
  getAllTitleSelector,
  TITLE_SELECTOR_MAPPING,
} from '../../../../../../../../types/constants/styles/title/config'
import { PageBaseStyles } from '../../../base'
import { TOOLBAR_THEME_STYLE } from '../../../common'
import { ConfigProcessor } from '../module/config_processor'
import {
  FeedbackTagType,
  GreasyForkUserType,
  ScriptFeedbackActionType,
  ScriptStatusActionType,
} from '../module/storage_process/types'

export class CommonPage {
  private readonly name: string = 'CommonPage'
  elements: GreasyForkElements = PAGE_ELEMENTS[SUPPORTED_PLATFORMS.GREASY_FORK]
  private readonly containerSelector = getElementSelector(this.elements, 'COMMON_CONTAINER')
  private static instance: CommonPage
  private readonly themeVarService: ThemeVarService = ThemeVarService.getInstance()
  private readonly stylesService: StylesService = StylesService.getInstance()
  private readonly pageHandler: PageHandler = PageHandler.getInstance()
  private readonly pageBaseStyles: PageBaseStyles = PageBaseStyles.getInstance()
  private readonly pageType = PageHandler.getCurrentPageType()

  /**
   * 获取单例实例
   */
  public static getInstance(): CommonPage {
    if (!CommonPage.instance) {
      CommonPage.instance = new CommonPage()
    }
    return CommonPage.instance
  }

  init(): void {
    this.initTitle()
    logger.attention(`[${this.name}] 标题样式初始化完成`)

    this.beautyButton()
    this.handleFileUploadedState()
  }

  /**
   * 初始化标题样式
   */
  initTitle(): void {
    const titleSelectorMapping = TITLE_SELECTOR_MAPPING[SUPPORTED_PLATFORMS.GREASY_FORK]

    Object.entries(titleSelectorMapping).forEach(([level, config]) => {
      if (!Object.keys(config).includes(this.pageType as GreasyForkPageType))
        return

      const titleClass = `${level === 'secondary' ? TITLE_STYLES.SECONDARY.className : TITLE_STYLES.TERTIARY.className} ${themeClassPrefix}-${ToolKit.browser.theme.getCurrentTheme()} ${BodyClasses.NO_DECORATION}`
      const titleSelector = config[this.pageType as GreasyForkPageType]

      if (!titleSelector)
        return

      $(titleSelector).addClass(titleClass)
    })
  }

  /**
   * 链接样式
   */
  linkStyles(): string {
    return this.stylesService.link.default()
  }

  /**
   * 功能性链接样式
   */
  functionalLinkStyles(): string {
    return `
color: var(--${PROJECT_PREFIX}-theme-text-secondary) !important;
text-decoration: none !important;
`
  }

  /**
   * 脚本列表项样式
   */
  scriptListStyles(): string {
    return `
border: none !important;
border-top: 1px solid var(--${PROJECT_PREFIX}-theme-border-primary) !important;
box-shadow: var(--${PROJECT_PREFIX}-theme-shadow-sm);
position: relative;
margin: 25px 20px !important;
border-left: 5px solid var(--${PROJECT_PREFIX}-theme-result-border-primary) !important;
transition: 0.3s ease;

&:hover {
  border-left-color: var(--${PROJECT_PREFIX}-theme-result-border-primary-hover) !important;
  box-shadow: var(--${PROJECT_PREFIX}-theme-code-shadow-hover) !important;
}

${this.scriptMetaStyles()}
`
  }

  scriptMetaStyles(): string {
    return `
article .script-meta-block {
  dt, dd {
    margin: 0;
    display: flex;
    align-items: center;
  }
  
  dt {
    font-weight: 500;
    color: var(--${PROJECT_PREFIX}-theme-text-secondary);
    
    span {
      display: inline-flex !important;
      align-items: center;
      justify-content: center;
      text-decoration: none !important;
      position: relative;
      color: var(--${PROJECT_PREFIX}-theme-text-primary) !important;
      
      &::before {
        ${this.stylesService.inlinePseudo.icon()}
      }
    }
  }
  
  dd {
    color: var(--${PROJECT_PREFIX}-theme-text-primary);
    font-weight: 500;
    span {
      white-space: nowrap;
    }
  }

  /* 作者 */
  .script-list-author {
    span::before {
      background-image: var(${this.themeVarService.generateIcon(ICON_IDS.role.author)}) !important;
    }
  }
  
  /* 评分 */
  .script-list-ratings {
    span::before {
      background-image: var(${this.themeVarService.generateIcon(ICON_IDS.action.star)}) !important;
    }
  }
  
  /* 日安装量 */
  .script-list-daily-installs {
    span::before {
      background-image: var(${this.themeVarService.generateIcon(ICON_IDS.action.download)}) !important;
    }
  }
  
  /* 总安装量 */
  .script-list-total-installs {
    span::before {
      background-image: var(${this.themeVarService.generateIcon(ICON_IDS.action.download)}) !important;
    }
  }
  
  /* 安装量级别标识 */
  dd.script-list-daily-installs span::after,
  dd.script-list-total-installs span::after {
    content: '';
    display: inline-block;
    margin-left: 4px;
    font-size: 0.8em;
    font-weight: bold;
    vertical-align: super;
  }

  ${ConfigProcessor.generateInstallLevelStyles()}
  
  /* 创建时间 */
  .script-list-created-date {
    span::before {
      background-image: var(${this.themeVarService.generateIcon(ICON_IDS.time.calendar)}) !important;
    }
  }
  
  /* 更新时间 */
  .script-list-updated-date  {
    span::before {
      background-image: var(${this.themeVarService.generateIcon(ICON_IDS.development.update)}) !important;
    }
  }
}    
`
  }

  baseStyles(): string {
    return `
  color: var(--${PROJECT_PREFIX}-theme-text-secondary) !important;
  p:not(${getAllAlertSelector()}) {
    color: var(--${PROJECT_PREFIX}-theme-text-secondary) !important;
  }
  
  & > h3:not(${getAllTitleSelector()}) {
    color: var(--${PROJECT_PREFIX}-theme-text-secondary) !important;
  }
  
  a {
    ${this.linkStyles()}
  }
`
  }

  /**
   * .text-content 页面样式
   */
  basePageStyles(): string {
    const PageConfig: Partial<Record<GreasyForkPageCategory, { container: string }>> = {
      [GreasyForkPageCategory.SIGN]: {
        container: '.text-content',
      },
      [GreasyForkPageCategory.USER]: {
        container: '.text-content',
      },
      [GreasyForkPageCategory.SCRIPT]: {
        container: '#script-info',
      },
      [GreasyForkPageCategory.DISCUSSION]: {
        container: '.text-content',
      },
      [GreasyForkPageCategory.REPORT]: {
        container: '.text-content',
      },
      [GreasyForkPageCategory.HELP]: {
        container: '.text-content',
      },
    }
    const config = PageConfig[getGreasyForkPageCategory(this.pageType as GreasyForkPageType)]

    if (!config)
      return ''

    const selectorMapping: Partial<Record<GreasyForkPageType, string>> = {
      [GreasyForkPageType.NOTIFICATIONS]: '.width-constraint',
    }
    const selector = selectorMapping[this.pageType as GreasyForkPageType] || config.container

    return `
${selector} {
  background-color: var(--${PROJECT_PREFIX}-theme-bg-base) !important;
  color: var(--${PROJECT_PREFIX}-theme-text-secondary) !important;
  border: none !important;
  box-shadow: none !important;
  margin-top: 0 !important;
  border-radius: 0 !important;
  
  p {
    margin-top: 0 !important;
    padding-top: 16px !important;
  }
  
  p:not(${getAllAlertSelector()}) {
    color: var(--${PROJECT_PREFIX}-theme-text-secondary) !important;
  }
  
  a {
    ${this.linkStyles()}
  }
  
  ul li {
    color: var(--${PROJECT_PREFIX}-theme-text-secondary) !important;
    
    &::marker{
      color: var(--${PROJECT_PREFIX}-theme-text-secondary) !important;
    }
  }
}
  `
  }

  /**
   * 浏览器列表样式
   */
  browserListStyles(): string {
    const supportPages = [
      GreasyForkPageType.INDEX,
      GreasyForkPageType.INSTALLING_USER_SCRIPTS,
    ]

    return !supportPages.includes(this.pageType as GreasyForkPageType)
      ? ''
      : `
.text-content .browser-list-selector {
  text-decoration: none !important;
  color: var(--${PROJECT_PREFIX}-theme-text-secondary) !important;
  border-bottom: 2px solid transparent !important;

  &.browser-list-selector-active {
    border-top: none !important;
    box-shadow: none !important;
    text-decoration: none !important;
    color: var(--${PROJECT_PREFIX}-theme-tab-active-text) !important;
    font-weight: bold !important;
    border-bottom: 2px solid var(--${PROJECT_PREFIX}-theme-tab-active-border) !important;
  }
  
  &:hover {
    color: var(--${PROJECT_PREFIX}-theme-tab-hover-text) !important;
  }
}
`
  }

  baseScriptContainerStyles(): string {
    const supportPages = [
      GreasyForkPageType.SCRIPT_INFO,
      GreasyForkPageType.SCRIPT_CODE,
      GreasyForkPageType.SCRIPT_VERSIONS,
      GreasyForkPageType.SCRIPT_FEEDBACK,
      GreasyForkPageType.SCRIPT_STATS,
      GreasyForkPageType.SCRIPT_DERIVATIVES,
      GreasyForkPageType.SCRIPT_VERSIONS_NEW,
      GreasyForkPageType.SCRIPT_DELETE,
      GreasyForkPageType.SCRIPT_ADMIN,
      GreasyForkPageType.SCRIPT_DIFF,
      GreasyForkPageType.SCRIPT_DISCUSSION,
      GreasyForkPageType.SCRIPT_LOCK_APPEALS,
    ]

    return !supportPages.includes(this.pageType as GreasyForkPageType)
      ? ''
      : `${this.containerSelector} {
  box-shadow: none !important;
  border: none !important;
  
  #script-links.tabs {
    a:hover {
      box-shadow: none !important;
      background: none !important;
    }
    
    a:focus {
      box-shadow: none !important;
      background: var(--${PROJECT_PREFIX}-theme-tab-focus-bg) !important;
      span {
        color: var(--${PROJECT_PREFIX}-theme-tab-active-text) !important;
      }
    }
    
    li {
      background: none !important;
    
      &:hover span {
        color: var(${this.themeVarService.link.default.text}) !important;
      }
      
      span {
        color: var(--${PROJECT_PREFIX}-theme-text-secondary) !important;
        border-bottom: 2px solid transparent !important;
      }
      
      &.current {
        border-top: none !important;
        box-shadow: none !important;
        margin: 7px 0 !important;
        
        span {
          color: var(--${PROJECT_PREFIX}-theme-tab-active-text) !important;
          font-weight: bold !important;
          border-bottom: 2px solid var(--${PROJECT_PREFIX}-theme-tab-active-border) !important;
        }
      }
    }
  }
  
  /* 页眉 */
  header {
    /* 标题 */
    h2 {
      color: var(--${PROJECT_PREFIX}-theme-text-primary) !important;
    }
    /* 脚本描述 */
    #script-description {
      color: var(--${PROJECT_PREFIX}-theme-text-secondary) !important;
    }
  }
  
  #script-content {
    ${this.baseStyles()}
  }
}`
  }

  baseListStyles(): string {
    const supportPages = [
      GreasyForkPageType.SCRIPT_LIST,
      GreasyForkPageType.SCRIPT_FEEDBACK,
      GreasyForkPageType.USER_PROFILE,
      GreasyForkPageType.USERS,
      GreasyForkPageType.LIBRARIES,
      GreasyForkPageType.DISCUSSIONS,
      GreasyForkPageType.DISCUSSIONS_GREASY_FORK,
      GreasyForkPageType.DISCUSSIONS_DEVELOPMENT,
      GreasyForkPageType.DISCUSSIONS_REQUESTS,
      GreasyForkPageType.DISCUSSIONS_SCRIPT,
      GreasyForkPageType.DISCUSSIONS_NO_SCRIPT,
    ]

    return !supportPages.includes(this.pageType as GreasyForkPageType)
      ? ''
      : `
display: grid !important;
position: relative !important;

margin: 20px 0 !important;
padding: 10px !important;
border-top: 1px solid var(--${PROJECT_PREFIX}-theme-border-primary) !important;
border-bottom: none !important;
box-shadow: var(--${PROJECT_PREFIX}-theme-shadow-sm);
border-left: 5px solid var(--${PROJECT_PREFIX}-theme-result-border-primary) !important;
transition: border-left-color 0.3s ease, box-shadow 0.3s ease !important;

&:hover {
  border-left-color: var(--${PROJECT_PREFIX}-theme-result-border-primary-hover) !important;
  box-shadow: var(--${PROJECT_PREFIX}-theme-code-shadow-hover) !important;
}
`
  }

  customScriptListStyles(): string {
    const supportPages = [
      GreasyForkPageType.SCRIPT_LIST,
      GreasyForkPageType.USER_PROFILE,
    ]

    return !supportPages.includes(this.pageType as GreasyForkPageType)
      ? ''
      : `
#browse-script-list, #user-script-list, #browse-user-list, #user-library-script-list {
  /* 结果列表 */
  li[data-script-id],li  {
    display: grid;
    grid-template-columns: auto 1fr;
    grid-template-rows: auto auto auto; /* 行数 */
    grid-template-areas:
      "index index"    /* 索引占据整行 */
      "avatar article" /* 头像和内容 */
      "avatar toolbar"; /* 头像和工具栏 */
    position: relative;
   
    /* 内容区域 */
    article {
      grid-area: article;
      min-width: 0; /* 防止内容溢出 */
    }
    
    /* 工具栏区域 */
    .custom-toolbar {
      grid-area: toolbar;
    }
  }
  
  /* 内容区域 */
  article {
    margin-bottom: 50px; /* 给工具栏留出空间*/
    
    ${this.getTagStyles()}
  }
}
`
  }

  /**
   * 获取标签样式
   */
  getTagStyles() {
    return `
.script-tags-container {
  display: flex;
  gap: 6px;
  flex-wrap: wrap;
  justify-content: flex-end;
  margin-left: auto;
  
  .script-tag {
    padding: 4px 8px;
    border-radius: 12px;
    font-size: 12px;
    font-weight: 600;
    color: #ffffff !important;
    box-shadow: 0 1px 3px rgba(0,0,0,0.1);
  }
  ${generateScriptTagStyles()}
}
`
  }

  scriptContainerStyles(): string {
    const supportPages = [
      GreasyForkPageType.SCRIPT_LIST,
      GreasyForkPageType.USER_PROFILE,
      GreasyForkPageType.LIBRARIES,
    ]

    return !supportPages.includes(this.pageType as GreasyForkPageType)
      ? ''
      : `
.sidebarred-main-content {
  ${this.baseStyles()}
  ${this.pageHandler.services.greasyFork.getScriptListSelector()} {
    ${this.scriptListStyles()}
  }
}
`
  }

  paginationStyles(): string {
    const supportPages = [
      GreasyForkPageType.SCRIPT_LIST,
      GreasyForkPageType.SCRIPT_VERSIONS,
      GreasyForkPageType.SCRIPT_FEEDBACK,
      GreasyForkPageType.DISCUSSIONS,
      GreasyForkPageType.DISCUSSIONS_GREASY_FORK,
      GreasyForkPageType.DISCUSSIONS_DEVELOPMENT,
      GreasyForkPageType.DISCUSSIONS_REQUESTS,
      GreasyForkPageType.DISCUSSIONS_SCRIPT,
      GreasyForkPageType.DISCUSSIONS_NO_SCRIPT,
      GreasyForkPageType.USERS,
      GreasyForkPageType.MODERATOR_ACTIONS,
      GreasyForkPageType.LIBRARIES,
    ]

    return !supportPages.includes(this.pageType as GreasyForkPageType)
      ? ''
      : `
${this.pageBaseStyles.pageBarStyles({
  container: '.pagination',
  currentPage: 'em.current',
  otherPage: 'a',
})}

.pagination {
  display: flex !important;
  justify-content: center !important;
  align-items: center !important;
  gap: ${this.themeVarService.pageBar.default.gap} !important;
  padding: ${this.themeVarService.default.style.padding} 0 !important;
  background-color: var(--${PROJECT_PREFIX}-theme-bg-base) !important;
  
  /* 上一页 */
  a.previous_page {
    padding: 0 ${this.themeVarService.pageBar.button.padding} !important;
  }
  
  /* 下一页 */
  a.next_page {
    padding: 0 ${this.themeVarService.pageBar.button.padding} !important;
  }
  
  /*其他页 */
  a:not(.next_page) {
  
  }
  
  /* 省略号 */
  .gap {
    color: var(${this.themeVarService.default.text.secondary}) !important;
  }
}
`
  }

  /**
   * 用户头像样式
   */
  avatarStyles(): string {
    const supportPages = [
      GreasyForkPageType.SCRIPT_LIST,
      GreasyForkPageType.SCRIPT_FEEDBACK,
      GreasyForkPageType.SCRIPT_DISCUSSION,
      GreasyForkPageType.USER_PROFILE,
      GreasyForkPageType.DISCUSSIONS,
      GreasyForkPageType.DISCUSSIONS_GREASY_FORK,
      GreasyForkPageType.DISCUSSIONS_DEVELOPMENT,
      GreasyForkPageType.DISCUSSIONS_REQUESTS,
      GreasyForkPageType.DISCUSSIONS_SCRIPT,
      GreasyForkPageType.DISCUSSIONS_NO_SCRIPT,
      GreasyForkPageType.USERS,
      GreasyForkPageType.LIBRARIES,
    ]

    if (!supportPages.includes(this.pageType as GreasyForkPageType)) {
      return ''
    }

    return this.pageHandler.features.user.getAvatarStyles()
  }

  /**
   * 搜索样式
   */
  searchStyles(enableBorder: boolean = true): string {
    return `
/* 移除所有状态下的边框 */
input[type="search"] {
  outline: none;
  box-shadow: none;
  ${enableBorder ? 'border: 1px solid #ccc; /* 保留普通状态下的边框 */' : ''}
}
`
  }

  scriptSearchStyles(): string {
    if (this.pageType === GreasyForkPageType.INDEX) {
      return `
#home-script-nav {
  .home-search {
    ${this.searchStyles()}
  }
}
`
    }

    if (this.pageType === GreasyForkPageType.BY_SITE) {
      return `
.text-content {
  ${this.searchStyles(false)}
}
`
    }

    const supportPages = [
      GreasyForkPageType.SCRIPT_LIST,
      GreasyForkPageType.USER_PROFILE,
      GreasyForkPageType.DISCUSSIONS,
      GreasyForkPageType.DISCUSSIONS_GREASY_FORK,
      GreasyForkPageType.DISCUSSIONS_DEVELOPMENT,
      GreasyForkPageType.DISCUSSIONS_REQUESTS,
      GreasyForkPageType.DISCUSSIONS_SCRIPT,
      GreasyForkPageType.DISCUSSIONS_NO_SCRIPT,
      GreasyForkPageType.USERS,
      GreasyForkPageType.LIBRARIES,
    ]

    return !supportPages.includes(this.pageType as GreasyForkPageType)
      ? ''
      : `
#script-list-option-groups, #user-list-option-groups, .list-option-groups {
  .sidebar-search {
    ${this.searchStyles()}
  }
}
`
  }

  scriptFilterStyles(): string {
    const supportPages = [
      GreasyForkPageType.SCRIPT_LIST,
      GreasyForkPageType.USER_PROFILE,
      GreasyForkPageType.DISCUSSIONS,
      GreasyForkPageType.DISCUSSIONS_GREASY_FORK,
      GreasyForkPageType.DISCUSSIONS_DEVELOPMENT,
      GreasyForkPageType.DISCUSSIONS_REQUESTS,
      GreasyForkPageType.DISCUSSIONS_SCRIPT,
      GreasyForkPageType.DISCUSSIONS_NO_SCRIPT,
      GreasyForkPageType.USERS,
      GreasyForkPageType.LIBRARIES,
    ]

    return !supportPages.includes(this.pageType as GreasyForkPageType)
      ? ''
      : `
#script-list-option-groups, .list-option-groups  {
  background-color: var(--${PROJECT_PREFIX}-theme-bg-base) !important;
  
  .list-option-group {
    color: var(--${PROJECT_PREFIX}-theme-text-secondary) !important;
    
    ul {
      background-color: transparent !important;
      border: none !important;
      box-shadow: none !important;
      
      li {
        &.list-current {
          background: transparent !important;
          color: var(--${PROJECT_PREFIX}-theme-text-primary) !important;
        }
        
        select {
          outline: none !important;
        }
        
        a {
          color: var(--${PROJECT_PREFIX}-theme-text-secondary) !important;
          
          &:hover, &:focus {
            color: var(${this.themeVarService.link.default.textHover}) !important;
            background: transparent !important;
            border: none !important;
            box-shadow: none !important;
          }
        }
      }
    }
  }
  
  #script-list-sort, #script-list-filter, #script-language-filter {
    color: var(--${PROJECT_PREFIX}-theme-text-secondary) !important;
  }
}
`
  }

  /**
   * 讨论标题样式
   */
  discussionTitleStyles(): string {
    const supportPages = [
      GreasyForkPageType.DISCUSSIONS,
      GreasyForkPageType.DISCUSSIONS_GREASY_FORK,
      GreasyForkPageType.DISCUSSIONS_DEVELOPMENT,
      GreasyForkPageType.DISCUSSIONS_REQUESTS,
      GreasyForkPageType.DISCUSSIONS_SCRIPT,
      GreasyForkPageType.DISCUSSIONS_NO_SCRIPT,
      GreasyForkPageType.SCRIPT_FEEDBACK,
    ]

    return !supportPages.includes(this.pageType as GreasyForkPageType)
      ? ''
      : `
.discussion-title {
  position: relative;
  word-wrap: break-word;
  white-space: normal;

  padding: 4px 0 60px !important;
  .discussion-snippet {
    color: var(--${PROJECT_PREFIX}-theme-text-secondary) !important;
  }

  /* 已评分 */
  &:has(.rating-icon) {
    display: flex;
    align-items: center;
    flex-direction: row;

    .rating-icon {
      display: flex;
      align-items: center;
      border: none !important;
      background: none !important;
      color: var(--${PROJECT_PREFIX}-theme-text-secondary) !important;
      min-width: unset !important;
      padding: 0 !important;

      &::before {
        ${this.stylesService.inlinePseudo.icon()}
      }
      
      &.rating-icon-good::before {
        background-image: var(${this.themeVarService.generateIcon(ICON_IDS.rating.good)}) !important;
      }
      &.rating-icon-bad::before {
        background-image: var(${this.themeVarService.generateIcon(ICON_IDS.rating.bad)}) !important;
      }
      &.rating-icon-ok::before {
        background-image: var(${this.themeVarService.generateIcon(ICON_IDS.rating.ok)}) !important;
      }
    }
  }
  
  /* 未评分 */
  &:not(:has(.rating-icon)) {
    display: flex;
    align-items: center;
    .discussion-snippet {
      display: flex;
      align-items: center;
      
      &::before {
        ${this.stylesService.inlinePseudo.icon({ size: 18, backgroundImageId: ICON_IDS.rating.unrated })}
      }
    }
  }
}
`
  }

  /**
   * 文本输入框样式
   */
  textareaStyles(): string {
    return `
margin: 10px 0 !important;
outline: none !important;
background: var(--${PROJECT_PREFIX}-theme-comment-bg) !important;
color: var(--${PROJECT_PREFIX}-theme-comment-text) !important;
border: 1px solid var(--${PROJECT_PREFIX}-theme-border-neutral) !important;
`
  }

  /**
   * 文本输入框页面样式
   */
  textareaPageStyles(): string {
    const supportPages = [
      GreasyForkPageType.SCRIPT_VERSIONS_NEW,
      GreasyForkPageType.SCRIPT_DISCUSSION,
      GreasyForkPageType.SCRIPT_FEEDBACK,
      GreasyForkPageType.EDIT,
      GreasyForkPageType.IMPORT,
      GreasyForkPageType.NEW_CSS,
      GreasyForkPageType.NEW_JS,
      GreasyForkPageType.DISCUSSIONS_NEW,
      GreasyForkPageType.DISCUSSIONS_DETAIL,
      GreasyForkPageType.REPORTS_NEW,
      GreasyForkPageType.USER_CONVERSATIONS,
    ]

    return !supportPages.includes(this.pageType as GreasyForkPageType)
      ? ''
      : `
.previewable, .text-content {
  textarea.comment-entry, 
  textarea[name="user[profile]"], 
  textarea[name="sync_urls"], 
  textarea#script_version_code,
  textarea#script-version-additional-info-0,
  textarea#conversation_messages_attributes_0_content,
  textarea#report_explanation,
  textarea#script_version_changelog,
  .preview-results {
    ${this.textareaStyles()}
  }
  .preview-results {
    background: var(--${PROJECT_PREFIX}-theme-bg-preview) !important;
  }
}
`
  }

  toolbarStyles(): string {
    const supportPages = [
      GreasyForkPageType.SCRIPT_LIST,
      GreasyForkPageType.SCRIPT_FEEDBACK,
      GreasyForkPageType.USER_PROFILE,
    ]

    return !supportPages.includes(this.pageType as GreasyForkPageType)
      ? ''
      : `
/* 工具栏 */
${this.pageHandler.services.greasyFork.getScriptListSelector()} {
  position: relative !important;
  
  ${TOOLBAR_THEME_STYLE}
  
  &[${ScriptDataMarkerType.MarkerSuccess}=${ScriptStatusActionType.MarkSuccess}], &[${ScriptDataMarkerType.MarkerSuccess}=${ScriptStatusActionType.MarkFailed}] {
    article h2 {
      position: relative;
      
      &::before {
        content: "";
        background-size: 64px 64px;
        background-repeat: no-repeat;
        position: absolute;
        width: 128px;
        height: 128px;
        right: 0;
        top: 0;
        opacity: 0.5;
        pointer-events: none;
      }
    }
  }
  &[${ScriptDataMarkerType.MarkerSuccess}=${ScriptStatusActionType.MarkSuccess}] article h2::before {
    background-image: var(${this.themeVarService.generateIcon(ICON_IDS.other.pass)}) !important;
  }
  &[${ScriptDataMarkerType.MarkerSuccess}=${ScriptStatusActionType.MarkFailed}] article h2::before {
    background-image: var(${this.themeVarService.generateIcon(ICON_IDS.other.expire)}) !important;
  }
  
  &[${ScriptDataMarkerType.MarkerLiker}=${ScriptFeedbackActionType.Like}], &[${ScriptDataMarkerType.MarkerLiker}=${ScriptFeedbackActionType.Dislike}] {
    &::before {
      content: "";
      background-size: 64px 64px;
      background-repeat: no-repeat;
      position: absolute;
      width: 128px;
      height: 128px;
      right: 0;
      bottom: 0;
      opacity: 0.8;
      pointer-events: none;
    }
  }
  &[${ScriptDataMarkerType.MarkerLiker}=${ScriptFeedbackActionType.Like}]::before {
    background-image: var(${this.themeVarService.generateIcon(ICON_IDS.rating.like)}) !important;
  }
  &[${ScriptDataMarkerType.MarkerLiker}=${ScriptFeedbackActionType.Dislike}]::before {
    background-image: var(${this.themeVarService.generateIcon(ICON_IDS.rating.dislike)}) !important;
  }
  
  ${this.highlightScriptResultStyle()}
}
`
  }

  /**
   * 高亮脚本结果样式
   */
  highlightScriptResultStyle(): string {
    return `    
      &[${ScriptDataMarkerType.MarkerLiker}=${ScriptFeedbackActionType.Like}],
      &[${ScriptDataMarkerType.MarkerSuccess}=${ScriptStatusActionType.MarkSuccess}] {
        ${this.highlightMarkStyle('success')}
      }
      
      &[${ScriptDataMarkerType.MarkerTypes}=${GreasyForkUserType.LoyalFan}] {
        ${this.highlightMarkStyle('purple')}
      }
      
      &[${ScriptDataMarkerType.MarkerTypes}=${GreasyForkUserType.Blacklisted}],
      &[${ScriptDataMarkerType.MarkerLiker}=${ScriptFeedbackActionType.Dislike}] {
        ${this.highlightMarkStyle('danger')}
      }
      
      &[${ScriptDataMarkerType.MarkerSuccess}=${ScriptStatusActionType.MarkFailed}] {
        ${this.highlightMarkStyle('warning')}
      }
    `
  }

  /**
   * 高亮反馈结果样式
   */
  highlightFeedbackResultStyle(): string {
    return `    
      &[${FeedbackDataMarkerType.MarkerTags}=${FeedbackTagType.Praise}] {
        ${this.highlightMarkStyle('success')}
      }
      
      &[${ScriptDataMarkerType.MarkerTypes}=${GreasyForkUserType.LoyalFan}] {
        ${this.highlightMarkStyle('purple')}
      }
      
      &[${ScriptDataMarkerType.MarkerTypes}=${GreasyForkUserType.Blacklisted}],
      &[${FeedbackDataMarkerType.MarkerTags}=${FeedbackTagType.Negative}],
      &[${FeedbackDataMarkerType.MarkerTags}=${FeedbackTagType.Malicious}] {
        ${this.highlightMarkStyle('danger')}
      }
    `
  }

  /**
   * 高亮标记样式
   */
  highlightMarkStyle(type: 'success' | 'danger' | 'warning' | 'purple'): string {
    return `
      border-left-color: var(${this.themeVarService.message[type].textSecondary}) !important;
      
      &:hover {
        border-left-color: var(${this.themeVarService.message[type].textPrimary}) !important;
      }
    `
  }

  inputStyles(): string {
    const PageConfig: Partial<Record<GreasyForkPageType, { container: string }>> = {
      [GreasyForkPageType.EDIT]: {
        container: '.text-content',
      },
      [GreasyForkPageType.EDIT_SIGN_IN]: {
        container: '.text-content',
      },
      [GreasyForkPageType.SETS_NEW]: {
        container: '.text-content',
      },
      [GreasyForkPageType.SIGN_UP]: {
        container: '.text-content',
      },
      [GreasyForkPageType.SIGN_IN]: {
        container: '.text-content',
      },
      [GreasyForkPageType.PASSWORD_NEW]: {
        container: '.text-content',
      },
      [GreasyForkPageType.PASSWORD_EDIT]: {
        container: '.text-content',
      },
      [GreasyForkPageType.DISCUSSIONS_NEW]: {
        container: '.text-content',
      },
      [GreasyForkPageType.SCRIPT_DELETE]: {
        container: '.width-constraint #script-content .form-control',
      },
      [GreasyForkPageType.SCRIPT_ADMIN]: {
        container: '.width-constraint #script-content .multiform-page',
      },
      [GreasyForkPageType.USER_CONVERSATIONS]: {
        container: '.text-content',
      },
    }
    const config = PageConfig[this.pageType as GreasyForkPageType]

    if (!config)
      return ''

    return `
${config.container} {
  input[type="text"], input[type="email"], input[type="password"], input[type="url"], input#replaced_by_script_id {
    ${this.stylesService.input.default}
  }
}
      `
  }

  // 测试链接：
  // 1）https://greasyfork.org/zh-CN/scripts/533339/discussions/307876
  userContentStyles(): string {
    const supportPages = [
      GreasyForkPageType.SCRIPT_DISCUSSION,
      GreasyForkPageType.DISCUSSIONS_DETAIL,
    ]

    return !supportPages.includes(this.pageType as GreasyForkPageType)
      ? ''
      : `
#script-info, .text-content {
  .user-content {
    blockquote {
      margin-left: unset !important;
    }
  }
}
      `
  }

  beautyButton(): void {
    const PageConfig: Partial<Record<GreasyForkPageType, { container: string }>> = {
      [GreasyForkPageType.SCRIPT_DISCUSSION]: {
        container: '.width-constraint #post-reply input[type="submit"]',
      },
      [GreasyForkPageType.SCRIPT_FEEDBACK]: {
        container: '.width-constraint .post-discussion input[type="submit"]',
      },
      [GreasyForkPageType.DISCUSSIONS_DETAIL]: {
        container: '.width-constraint #post-reply input[type="submit"]',
      },
      [GreasyForkPageType.DISCUSSIONS_NEW]: {
        container: '.width-constraint .post-discussion #new-discussion input[type="submit"]',
      },
      [GreasyForkPageType.DELETE_INFO]: {
        container: '.width-constraint form input[type="submit"]',
      },
      [GreasyForkPageType.EDIT]: {
        container: '.width-constraint .edit_user input[type="submit"]',
      },
      [GreasyForkPageType.EDIT_SIGN_IN]: {
        container: '.width-constraint input[type="submit"][value="更新密码"]',
      },
      [GreasyForkPageType.IMPORT]: {
        container: '.width-constraint form input[type="submit"]',
      },
      [GreasyForkPageType.NEW_CSS]: {
        container: '.width-constraint input[type="submit"]',
      },
      [GreasyForkPageType.NEW_JS]: {
        container: '.width-constraint input[type="submit"]',
      },
      [GreasyForkPageType.SETS_NEW]: {
        container: '.width-constraint .change-script-set button[name="save"]',
      },
      [GreasyForkPageType.SIGN_UP]: {
        container: '.width-constraint .button[type="submit"]',
      },
      [GreasyForkPageType.WEBHOOK_INFO]: {
        container: '.width-constraint dd form input[type="submit"]',
      },
      [GreasyForkPageType.REPORTS_NEW]: {
        container: '.width-constraint .text-content input[type="submit"]',
      },
      [GreasyForkPageType.SCRIPT_DERIVATIVES]: {
        container: '.width-constraint #script-content .button_to button[type="submit"]',
      },
      [GreasyForkPageType.SCRIPT_VERSIONS_NEW]: {
        container: '.width-constraint #script-content .new_script_version input[type="submit"]',
      },
      [GreasyForkPageType.SCRIPT_DELETE]: {
        container: '.width-constraint #script-content input[type="submit"]',
      },
      [GreasyForkPageType.SCRIPT_ADMIN]: {
        container: '.width-constraint #script-content input[type="submit"]',
      },
    }
    const config = PageConfig[this.pageType as GreasyForkPageType]

    if (!config)
      return

    $(config.container).addClass(`btn ${BUTTON_STYLES.primary.className}`)
  }

  /**
   * 处理文件上传状态
   */
  handleFileUploadedState(): void {
    const supportPages = [
      GreasyForkPageType.SCRIPT_FEEDBACK,
      GreasyForkPageType.SCRIPT_VERSIONS_NEW,
      GreasyForkPageType.SCRIPT_DISCUSSION,
      GreasyForkPageType.DISCUSSIONS_NEW,
      GreasyForkPageType.DISCUSSIONS_DETAIL,
      GreasyForkPageType.REPORTS_NEW,
      GreasyForkPageType.USER_CONVERSATIONS,
    ]

    if (!supportPages.includes(this.pageType as GreasyForkPageType))
      return

    $(`.width-constraint .${this.getFileUploadContainerClass()} input[type="file"]`).on('change', (e) => {
      const $element = $(e.currentTarget)
      const value = $element.val()
      $element.toggleClass('file-uploaded', !!value)
    })
  }

  fileUploadStyles(): string {
    const PageConfig: Partial<Record<GreasyForkPageType, { container: string }>> = {
      [GreasyForkPageType.SCRIPT_FEEDBACK]: {
        container: '#new-script-discussion',
      },
      [GreasyForkPageType.SCRIPT_VERSIONS_NEW]: {
        container: '#script-content',
      },
      [GreasyForkPageType.SCRIPT_DISCUSSION]: {
        container: '#new-discussion, #post-reply',
      },
      [GreasyForkPageType.DISCUSSIONS_NEW]: {
        container: '.text-content',
      },
      [GreasyForkPageType.DISCUSSIONS_DETAIL]: {
        container: '.text-content',
      },
      [GreasyForkPageType.REPORTS_NEW]: {
        container: '.text-content',
      },
      [GreasyForkPageType.USER_CONVERSATIONS]: {
        container: '.text-content',
      },
    }

    const BASE_STYLES = `
.${this.getFileUploadContainerClass()} {
  display: flex;
  flex-direction: column;
  gap: 10px;
  
  input[type="file"].${BodyClasses.FILE_UPLOADED} {
    color: var(${this.themeVarService.link.default.text}) !important;
  }
}
    `

    const config = PageConfig[this.pageType as GreasyForkPageType]

    if (!config)
      return ''

    return `
${config.container} {
  ${BASE_STYLES}
}
    `
  }

  getFileUploadContainerClass(): string {
    switch (this.pageType) {
      case GreasyForkPageType.SCRIPT_VERSIONS_NEW:
        return 'script-screenshot-control'
      case GreasyForkPageType.REPORTS_NEW:
        return 'report-screenshot-control'
      default:
        return 'comment-screenshot-control'
    }
  }

  getMainStyles(): string {
    return `
${this.basePageStyles()}
${this.browserListStyles()}
${this.baseScriptContainerStyles()}
${this.customScriptListStyles()}
${this.scriptContainerStyles()}
${this.scriptSearchStyles()}
${this.scriptFilterStyles()}
${this.paginationStyles()}
${this.avatarStyles()}
${this.discussionTitleStyles()}
${this.textareaPageStyles()}
${this.toolbarStyles()}
${this.inputStyles()}
${this.userContentStyles()}
${this.fileUploadStyles()}
`
  }
}
